package com.beimihu.leetcode.数据结构;

public class SinglyLinkList {
    private Node head = new Node(5,null);
    class Node{
        int value;
        Node next;
        public Node(int value,Node next){
            this.value = value;
            this.next = next;
        }
    }

    public void addFirst(int value){
//        head = new Node (value,head);
        insert(0,value);
    }

    public void loop(){
        Node p = head.next;
        while(p != null){
            System.out.println(p.value);
            p = p.next;
        }
    }
    public void addLast(int value){
        Node last = findLast();
        last.next = new Node(value,null);

    }
    private Node findLast(){
        Node p ;
        for(p = head;p.next != null;p = p.next ){

        }
        return p;
    }

    public Node findNode(int index){
        int i = -1;
        for(Node p = head;p != null ;p = p.next,i++){
            if(i == index){
                return p;
            }
        }
        return null;
    }
    private int get(int index){
        Node p = findNode(index);
        if (p == null){
            throw new IllegalArgumentException("下标越界");
        }
        return p.value;
    }
    private void insert(int index, int value){
        Node prev = findNode(index -1);
        if (prev == null){
            throw new IllegalArgumentException("下标越界");
        }
        prev.next = new Node(value,prev.next);
    }

    private void removeFirst(){
        if (head == null){
            throw new IllegalArgumentException("下标越界");
        }
        head = head.next;
    }

    private void remove(int index){
        Node prev = findNode(index - 1);
        if (prev == null){
            throw new IllegalArgumentException("下标越界");
        }
        Node removed = prev.next;
        if (removed == null){
            throw new IllegalArgumentException("下标越界");
        }
        prev.next = removed.next;
    }
}
